#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import os
sys.path.append("./src")
import sqliteWrite
import cherrypy		#sudo aptitude install python-cherrypy3
import html
import tools
import json
import threading
import pytz
import datetime
import time
import email_help
import getpass

psqlMgr = sqliteWrite.sqliteWrite('db/waterDB')
if os.getcwd() == '/home/iamar/webapps/waterlily/waterLily_1': hostPort = 32361
elif os.getcwd() == '/home/iamar/webapps/test_water/waterLily_2': hostPort = 12028
else: hostPort = 8080

key = ''
if os.path.exists('src/pinp'):
	fin = open('src/pinp', 'r')
	key = fin.read().strip()
	fin.close()
else:
	key = getpass.getpass('\n\nPlease enter the password of the database (my data), or using a pinp file with pswd: ')



class loop_thread(threading.Thread):
	def __init__(self):
		threading.Thread.__init__(self)
		self.addr = 'appointment@waterlilywellness.com' 
		self.img = './img/bizcardclean.png'

	def run(self):
		global hostPort
		rm_ap = '<!-- remove appointment link -->'

		doc_info = psqlMgr.query('select * from doctors where email="kathia@waterlilywellness.com"')
		doc_info = doc_info[0]

		while True:
			currentTime = datetime.datetime.now(pytz.timezone('US/Eastern'))
			day_after = currentTime + datetime.timedelta(days=1)
			y = day_after.year
			m = day_after.month
			d = day_after.day

			cmd = 'select * from appointments where '
			cmd += 'day="' + str(d) + '" and month="' + str(m) + '" and year="' + str(y) 
			cmd += '" and status="confirmed" and reminder_status=""'
			#cmd += '" and status="confirmed"'
			appoints = psqlMgr.query(cmd)

			for i in appoints:
				appointment_day = str(i['month']) + '/' + str(i['day']) + '/' + str(i['year'])
				appointment_hour = tools.get_Time_string(i['hour'], i['minute'])

				msg = email_help.email_contact(psqlMgr, './html/reminder_email.html', i['uuid'], hostPort)
				i['reminder_status'] = 'tomorrow notice'

				psqlMgr.updateTable('appointments', i)
				tools.mail(i['email'], 'You have an acupuncture appointment tomorrow', msg, 'chieh', key, self.addr, self.img)
				time.sleep(3)

			time.sleep(3)


loop = loop_thread()
loop.setDaemon(True)
loop.start()



class waterLily(object):
	addr = 'appointment@waterlilywellness.com' 
	img = './img/bizcardclean.png'

	def index(self):
		content = html.read_basic_html('html/waterlilyWellness.html', {})
		return content

	def default(self, userDomain, *args, **kwargs):
		content = html.read_basic_html('html/page_missing.html', {})
		return content

	def on_credentials(self):
		content = html.read_basic_html('html/on_credentials.html', {})
		return content


	def on_whatis(self):
		content = html.read_basic_html('html/on_whatis.html', {})
		return content


	def on_expectations(self):
		content = html.read_basic_html('html/on_expectations.html', {})
		return content

	def on_specialties(self):
		content = html.read_basic_html('html/on_specialties.html', {})
		return content

	def acupuncture(self):
		content = html.read_basic_html('html/acupuncture.html', {})
		return content

	def on_herbal(self):
		content = html.read_basic_html('html/on_herbal.html', {})
		return content

	def services(self):
		content = html.read_basic_html('html/services.html', {})
		return content

	def on_resources(self):
		content = html.read_basic_html('html/resources.html', {})
		return content

	def on_jesse(self):
		content = html.read_basic_html('html/jesse.html', {})
		return content

	def on_kathia(self):
		content = html.read_basic_html('html/kathia.html', {})
		return content

	def on_appointment(self):
		analytics = html.read_basic_html('html/analytics_track.html', {})

		content = html.read_basic_html('html/on_appointment.html', {})
		content = content.replace('<!-- analytics -->', analytics)
		return content

	def on_calendar(self):
		analytics = html.read_basic_html('html/analytics_track.html', {})

		content = html.read_basic_html('html/on_calendar.html', {})
		content = content.replace('<!-- analytics -->', analytics)
		return content

	def on_FAQ(self):
		analytics = html.read_basic_html('html/analytics_track.html', {})

		content = html.read_basic_html('html/on_FAQ.html', {})
		content = content.replace('<!-- analytics -->', analytics)
		return content

	def on_contact(self):
		content = html.read_basic_html('html/on_contact.html', {})
		return content

	def on_rates(self):
		analytics = html.read_basic_html('html/analytics_track.html', {})

		content = html.read_basic_html('html/on_rates.html', {})
		content = content.replace('<!-- analytics -->', analytics)
		return content


	def on_submit_appointment(self, data):
		global key
		global hostPort

		uuid = tools.getRandomStr(32, '', '')

		data = tools.SafeStringToSpecial(data)
		json_data = json.loads(data)
		json_data['uuid'] = uuid
		json_data['status'] = 'unconfirmed'
		json_data['title'] = 'Booked'

		appointment_day = str(json_data['month']) + '/' + str(json_data['day']) + '/' + str(json_data['year'])
		appointment_hour = tools.get_Time_string(json_data['hour'], json_data['minute'])

		#for m,j in json_data.items():
		#	print m, j

		psqlMgr.updateTable('appointments', json_data)
		doc_info = psqlMgr.query('select * from doctors where email="kathia@waterlilywellness.com"')
		doc_info = doc_info[0]

		msg = email_help.email_contact(psqlMgr, './html/confirm_email.html', uuid, hostPort)
		tools.mail(json_data['email'], 'Please confirm your appointment', msg, 'chieh', key, waterLily.addr, waterLily.img)

		return uuid

	def get_day_data(self, d, m, y, uuid, access):
		cmd = 'select * from appointments where '
		cmd += 'day="' + str(d) + '" and month="' + str(m) + '" and year="' + str(y) + '" and status="confirmed"'

		accessType = 'manager'
		if self.check_wrong_access(uuid, access): accessType = 'user'

		appoints = psqlMgr.query(cmd)
		appoint_list = []	
		for m in appoints:
			if accessType == 'manager':
				m['title'] = m['first_name'] + ' ' + m['last_name'] + ' , ' + m['phone_number'] + ' , ' + m['email'] + ' , '
				m['title'] += m['session_type'] + ' , ' + m['visit_reason']
				m['end'] = m['ends']
				m['allDay'] = False
				appoint_list.append(m)
			else:
				new_appoint = {}
				new_appoint['title'] = m['title']
				new_appoint['start'] = m['start']
				new_appoint['end'] = m['ends']
				new_appoint['allDay'] = False

				appoint_list.append(new_appoint)

		return json.dumps(appoint_list)

	def doube_booked(self, appoints):
		content = html.read_basic_html('html/double_booked.html', {})

		title = 'We have cancelled your appointment'

		msg = email_help.email_contact(psqlMgr, 'html/cancel_appointment_email.html', appoints['uuid'], hostPort)
		tools.mail(appoints['email'], title, msg, 'chieh', key, waterLily.addr, waterLily.img)
		return content 

	def confirm_appointment(self, uuid):
		global hostPort
		content = html.read_basic_html('html/confirm.html', {})

		doc_info = psqlMgr.query('select * from doctors where email="kathia@waterlilywellness.com"')
		doc_info = doc_info[0]

		appoints = psqlMgr.query('select * from appointments where uuid="' + uuid + '"')
		if len(appoints) == 0:
			return 'This appointment does not exist'
		appoints = appoints[0]

		time_constant_start = appoints['hour']*60 + appoints['minute']
		time_constant_end = time_constant_start + int(appoints['session_time'])
		time_constant_mid = (time_constant_start + time_constant_end)/2
		time_constant_radius = time_constant_end - time_constant_mid

		cmd = 'select * from appointments where day="' + str(appoints['day']) + '" and month="' + str(appoints['month']) + '" '
		cmd += 'and status="confirmed"'
		all_appoints = psqlMgr.query(cmd)
		for a in all_appoints:
			if a['uuid'] != uuid:
				start = a['hour']*60 + a['minute']
				end = start + int(a['session_time'])
				mid = (start + end)/2
				radius = end - mid

				if abs(time_constant_mid - mid) < (time_constant_radius + radius):
					return self.doube_booked(appoints)


		content = content.replace('<patient>',  appoints['first_name'])
		content = content.replace('<appointment_day>',  	str(appoints['day']))
		content = content.replace('<appointment_month>',  	str(appoints['month']))
		content = content.replace('<appointment_year>',  	str(appoints['year']))
		content = content.replace('<appointment_hour>',  	str(appoints['hour']))
		content = content.replace('<appointment_min>',  	str(appoints['minute']))
		content = content.replace('<doctor>',  				doc_info['name'])
		content = content.replace('<address>',  			doc_info['address'])
		content = content.replace('<gmap_embed>',  			doc_info['gmap_embed'])

		if(appoints['status'] == 'confirmed'): return content

		appoints['status'] = 'confirmed'
		psqlMgr.updateTable('appointments', appoints)

		msg = email_help.email_contact(psqlMgr, 'html/tell_kathia.html', uuid, hostPort)
		date = str(appoints['month']) + '/' + str(appoints['day']) + '/' + str(appoints['year'])
		title = 'Appointment : ' + appoints['first_name'] + ' ' + appoints['last_name'] + ' , ' + date
		tools.mail(doc_info['primary_email'], title, msg, 'chieh', key, waterLily.addr, waterLily.img)
		return content

	
	def doctor_remove_appointment(self, uuid):
		appoints = psqlMgr.query('select * from appointments where uuid="' + uuid + '"')
		if len(appoints) == 0:
			return 'This appointment does not exist'
		appoints = appoints[0]

		appoints['status'] = 'cancelled'
		psqlMgr.updateTable('appointments', appoints)

		return 'Appointment cancelled'

	def remove_appointment(self, uuid):
		appoints = psqlMgr.query('select * from appointments where uuid="' + uuid + '"')
		if len(appoints) == 0:
			return 'This appointment does not exist'
		appoints = appoints[0]

		content = html.read_basic_html('html/cancel.html', {})

		appoints['status'] = 'cancelled'
		psqlMgr.updateTable('appointments', appoints)

		return content

	def get_doctor_data(self):
		currentTime = datetime.datetime.now(pytz.timezone('US/Eastern'))
		one_months_after = currentTime + datetime.timedelta(days=29)

		m = currentTime.month
		m_1 = one_months_after.month

		appoints = psqlMgr.query('select first_name, start, ends, hour, minute, status from appointments where (month="' + str(m) + '" or month="' + str(m_1) + '") and status="confirmed"')

		appoint_list = []	
		for m in appoints:
			new_appoint = {}
			new_appoint['title'] = m['first_name'] #tools.get_Time_string(m['hour'], m['minute'])
			new_appoint['start'] = m['start']
			new_appoint['end'] = m['ends']
			new_appoint['allDay'] = False
			appoint_list.append(new_appoint)


		source = 'exception_days, uuid, monday_start, monday_end, tuesday_start, tuesday_end, wednesday_start, wednesday_end, '
		source += 'thursday_start, thursday_end, friday_start, friday_end, saturday_start, saturday_end, sunday_start, sunday_end'
		doc_info = psqlMgr.query('select ' + source + ' from doctors where email="kathia@waterlilywellness.com"')
		doc_info = doc_info[0]
		return json.dumps([doc_info, appoint_list])

	def login_page(self):
		content = html.read_basic_html('html/login_page.html', {})
		return content

	def thank_you(self, uuid):
		content = html.read_basic_html('html/thankyou.html', {})

		doc_info = psqlMgr.query('select * from doctors where email="kathia@waterlilywellness.com"')
		doc_info = doc_info[0]

		appoints = psqlMgr.query('select * from appointments where uuid="' + uuid + '"')
		if len(appoints) == 0:
			return content
		appoints = appoints[0]

		content = content.replace('<patient>',  appoints['first_name'])
		content = content.replace('<appointment_day>',  	str(appoints['day']))
		content = content.replace('<appointment_month>',  	str(appoints['month']))
		content = content.replace('<appointment_year>',  	str(appoints['year']))
		content = content.replace('<appointment_hour>',  	str(appoints['hour']))
		content = content.replace('<appointment_min>',  	str(appoints['minute']))
		content = content.replace('<doctor>',  				doc_info['name'])
		content = content.replace('<address>',  			doc_info['address'])
		content = content.replace('<gmap_embed>',  			doc_info['gmap_embed'])
		content = content.replace('<email>',  				appoints['email'])

		return content

	def on_login(self,login_data):
		login_data = json.loads(login_data)
		cmd = 'select * from doctors where primary_email="' + login_data['name'] + '" and pswd="' + login_data['password'] + '"'
		doc_info = psqlMgr.query(cmd)
		if len(doc_info) == 0:
			return '0'

		doc_info = doc_info[0]
		access_string = tools.getRandomStr(10, '', '')
		doc_info['access_string'] = access_string
		psqlMgr.updateTable('doctors', doc_info)

		return 'manage_page?uuid=' + doc_info['uuid'] + '&access=' + access_string

	def check_wrong_access(self, uuid, access):
		cmd = 'select * from doctors where uuid="' + uuid + '" and access_string="' + access + '"'
		doc_info = psqlMgr.query(cmd)
		if len(doc_info) == 0: 
			return True
		return False

	def manage_page(self, uuid, access):
		if self.check_wrong_access(uuid, access): return html.read_basic_html('html/page_missing.html', {})
		content = html.read_basic_html('html/manage_page.html', {})
		return content

	def on_operation_hour(self, uuid, access):
		if self.check_wrong_access(uuid, access): return html.read_basic_html('html/page_missing.html', {})
		content = html.read_basic_html('html/on_operation_hour.html', {})
		return content

	def on_schedule(self, uuid, access):
		if self.check_wrong_access(uuid, access): return html.read_basic_html('html/page_missing.html', {})
		content = html.read_basic_html('html/on_schedule.html', {})
		return content


	def even_fetch(self, start, end, _):

		test = "{"
		test += "    events: ["
		test += "				{"
		test += "					title: 'Long Event',"
		test += "					start: new Date(2014, 2, 5, 11, 0),"
		test += "					end: new Date(2014, 2, 5, 12, 0),"
		test += "				},"
		test += "				{"
		test += "					title: 'Long Event',"
		test += "					start: new Date(2014, 3, 5, 11, 0),"
		test += "					end: new Date(2014, 3, 5, 12, 0),"
		test += "				}"
		test += ""
		test += "    ],"
		test += "    color: 'yellow',   // an option!"
		test += "    textColor: 'black' // an option!"
		test += "}"

		print start
		print end
		return test

	
	def online_form(self):
		content = html.read_basic_html('html/online_form.html', {})
		return content 

	def update_doctor_info(self, uuid, access, doctor_data):
		if self.check_wrong_access(uuid, access): 
			retVal = {}
			retVal['type'] = 'error'
			retVal['msg'] = 'Your session has expired, please login again.'
			return json.dumps(retVal)

		doctor_data = tools.SafeStringToSpecial(doctor_data)
		doctor_data = json.loads(doctor_data)
		psqlMgr.updateTable('doctors', doctor_data)

		retVal = {}
		retVal['type'] = 'ok'
		return json.dumps(retVal)

#	new function here
	on_resources.exposed = True
	on_jesse.exposed = True
	on_whatis.exposed = True
	on_expectations.exposed = True
	on_specialties.exposed = True
	on_credentials.exposed = True
	on_specialties.exposed = True
	doctor_remove_appointment.exposed = True
	update_doctor_info.exposed = True
	on_operation_hour.exposed = True
	online_form.exposed = True
	even_fetch.exposed = True
	default.exposed = True
	on_schedule.exposed = True
	manage_page.exposed = True
	on_login.exposed = True
	login_page.exposed = True
	get_doctor_data.exposed = True
	on_rates.exposed = True
	thank_you.exposed = True
	confirm_appointment.exposed = True
	remove_appointment.exposed = True
	get_day_data.exposed = True
	on_submit_appointment.exposed = True
	on_contact.exposed = True
	on_FAQ.exposed = True
	on_calendar.exposed = True
	on_appointment.exposed = True
	on_kathia.exposed = True
	services.exposed = True
	acupuncture.exposed = True
	on_herbal.exposed = True
	index.exposed = True



if __name__ == '__main__':
	current_dir = os.path.dirname(os.path.abspath(__file__))
				 
	
	conf = 	{
				'/': {'tools.encode.on':True, 'tools.encode.encoding':'utf-8', 'tools.proxy.on':True},
				'/': {'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join(current_dir, '')},
				'/html': {'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join(current_dir, 'html'), 'tools.staticdir.content_types': {'css': 'text/css', 'manifest': 'text/cache-manifest'}},
				'/img': {'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join(current_dir, 'img')},
				'/raw_materials': {'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join(current_dir, 'raw_materials')},
				'/css': {'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join(current_dir, 'css')},
				 'global':	{ 'server.environment': 'production',
				'engine.autoreload_on': True,
				'engine.autoreload_frequency': 5,
				'server.socket_host': '0.0.0.0',
				'server.socket_port': hostPort}
			}
	
	cherrypy.quickstart(waterLily(), '/', config=conf)

	



